package com.star.oauth2.resource.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

/**
 * 资源服务器安全配置
 * 
 * 配置内容：
 * 1. 启用JWT令牌验证
 * 2. 配置API访问权限
 * 3. 启用方法级安全注解
 * 
 * @author star
 */
@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class ResourceServerConfig {

    /**
     * 资源服务器安全配置
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        // 公开端点
                        .requestMatchers("/", "/error", "/favicon.ico").permitAll()
                        // API端点需要认证
                        .requestMatchers("/api/**").authenticated()
                        // 其他请求需要认证
                        .anyRequest().authenticated()
                )
                // 配置为OAuth2资源服务器，使用JWT
                // JWT将从配置文件中的issuer-uri自动获取公钥来验证令牌
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(Customizer.withDefaults())
                );
        
        return http.build();
    }

}

